//
//  UserOperator.swift
//  COpenSSL
//
//  Created by 陈志勇 on 2018/11/10.
//
import PerfectLogger

class UserOperator: BaseOperator {
    let userTableName = "user"
    
    func insertUserInfo(userName: String, password: String) -> String? {
        let value = "('\(userName)', '\(password)')"
        let statement = "insert into \(userTableName) (username, password) values \(value)"
        LogFile.info("执行SQL: \(statement)")
        if !mysql.query(statement: statement) {
            LogFile.error("\(statement)插入失败")
            responseJson[ResultKey] = RequestResultFaile
            responseJson[ErrorMessageKey] = "创建\(userName)失败"
            guard let json = try? responseJson.jsonEncodedString() else {
                return nil
            }
            return json
        }else {
            LogFile.info("插入\(userName)成功")
            return queryUserInfo(userName: userName)
        }
    }
    
    func deleteUser(userID: String) -> String? {
        let statement = "delete from \(userTableName) where id = '\(userID)'"
        LogFile.info("执行SQL: \(statement)")
        if !mysql.query(statement: statement) {
            LogFile.error("\(statement)删除失败")
            responseJson[ResultKey] = RequestResultFaile
            responseJson[ErrorMessageKey] = "创建失败"
        }else {
            LogFile.info("SQL:\(statement) 删除成功")
            responseJson[ResultKey] = RequestResultSuccess
        }
        
        guard let json = try? responseJson.jsonEncodedString() else {
            return nil
        }
        return json
    }
    
    func updateUserInfo(userID: String, userName: String, password: String) -> String? {
        let statement = "update \(userTableName) set userName = '\(userName)', password = '\(password)', create_time=now() where id = '\(userID)'"
        LogFile.info("执行SQL: \(statement)")
        if !mysql.query(statement: statement) {
            LogFile.error("\(statement)更新失败")
            responseJson[ResultKey] = RequestResultFaile
            responseJson[ErrorMessageKey] = "更新失败"
            guard let json = try? responseJson.jsonEncodedString() else {
                return nil
            }
            return json
        }else {
            LogFile.info("SQL:\(statement) 更新成功")
            return queryUserInfo(userName: userName)
        }
    }
    
    func queryUserInfo(userName: String) -> String? {
        let statement = "select id, username, password, register_date from \(userTableName) where username = '\(userName)'"
        LogFile.info("执行SQL: \(statement)")
        if !mysql.query(statement: statement) {
            LogFile.error("\(statement)查询失败")
            responseJson[ResultKey] = RequestResultFaile
            responseJson[ErrorMessageKey] = "查询失败"
        }else {
            LogFile.info("SQL:\(statement) 查询成功")
            let results = mysql.storeResults()!
            
            var dic = [String:String]()
            results.forEachRow { (row) in
                guard let userID = row.first! else {
                    return
                }
                dic["userID"] = "\(userID)"
                dic["userName"] = "\(row[1]!)"
                dic["password"] = "\(row[2]!)"
                dic["register_date"] = "\(row[3]!)"
            }
            responseJson[ResultKey] = RequestResultSuccess
            responseJson[ResultListKey] = dic
        }
        guard let json = try? responseJson.jsonEncodedString() else {
            return nil
        }
        return json
    }
    
    func queryUserInfo(userName: String, password: String) -> String? {
        let statement = "select * from user where username = '\(userName)' and password = '\(password)'"
        LogFile.info("执行SQL: \(statement)")
        if !mysql.query(statement: statement) {
            LogFile.error("\(statement)查询失败")
            responseJson[ResultKey] = RequestResultFaile
            responseJson[ErrorMessageKey] = "查询失败"
        }else {
            LogFile.info("SQL:\(statement) 查询成功")
            let results = mysql.storeResults()!
            
            var dic = [String:String]()
            if results.numRows() == 0 {
                LogFile.error("\(statement) 用户名或密码错误，请重新输入")
                responseJson[ResultKey] = RequestResultFaile
                responseJson[ErrorMessageKey] = "用户名或密码错误，请重新输入"
            }else {
                results.forEachRow { (row) in
                    guard let userID = row.first! else {
                        return
                    }
                    dic["userID"] = "\(userID)"
                    dic["userName"] = "\(row[1]!)"
                    dic["register_date"] = "\(row[3]!)"
                }
            }
            
            responseJson[ResultKey] = RequestResultSuccess
            responseJson[ResultListKey] = dic
        }
        guard let json = try? responseJson.jsonEncodedString() else {
            return nil
        }
        return json
    }
}
